package product;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;

import jxl.Workbook;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class Stock extends JInternalFrame { // 좌클릭과 우클릭의 기능을 다르게도 가능(ex)좌클릭=현재 테이블 변환, 우클릭=팝업창으로
	//ex)좌클릭은 배열, 우클릭은 해쉬맵으로, 결과내 검색, 창에서 창 띄우기

	private JPanel contentPane;
	private JPanel panel;
	private JButton btnScan;
	private JScrollPane scrollPane;
	private JTable table;
	
	File f;
	FileInputStream fis;
	ObjectInputStream ois;
	Vector<ProductData> v;
	Vector<SaleData> v2;
	Vector vv;
	ArrayList<ProductData> pList;
	ArrayList sList;
	HashMap sTotal;
	HashMap<String, ProductData> join;
	String findText;
	boolean eScan=false;
	boolean gum1 = false;
	boolean gum2 = false;
	boolean gum3 = false;
	
	Stock2 tb = null;
	GraphicsObjectEx test = null;
	
	DefaultTableModel model;
	int columnX;
	int rowY;
	String value;
	private static int tbCount = 1; // 객체 카운트도 포함됨
	
	String FilePath = "C:\\data.xls"; //파일경로 및 파일명
	String SheetName = "stock"; //시트이름
	int cnt; //엑셀저장버튼 누른수.
	
	private JMenuBar menuBar;
	private JPanel panel_1;
	private JLabel lblNewLabel;
	private JLabel lblNewLabel_1;
	private JLabel lblNewLabel_3;
	private JButton btnNewButton;
	private JButton button;
	private JPanel panel_2;
	private JComboBox comboBox_1;
	private JComboBox comboBox_2;
	private JComboBox comboBox_3;
	private JTextField textScan;
	private JLabel label;
	private JLabel lblNewLabel_2;
	private JLabel label_1;
	private JButton btnSaveExcel;

	int circlePro;
	int circleJeago;
	private JButton btnNewButton_1;
	private JButton btnNewButton_2;

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Stock frame = new Stock();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public Stock() {
		super("2조 재고", true, true, true, false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(0, 0, 525, 291);
		setJMenuBar(getMenuBar_1());
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getScrollPane(), BorderLayout.CENTER);
//		contentPane.add(getBtnSaveExcel(), BorderLayout.SOUTH);

	}
	
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getBtnScan(), BorderLayout.EAST);
			panel.add(getPanel_2(), BorderLayout.CENTER);
		}
		return panel;
	}
	private JButton getBtnScan() {
		if (btnScan == null) {
			btnScan = new JButton("조회");
			btnScan.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
//					if (textScan.getText().equals("")) {
//						findText=textScan.getText();
//						scan();
//					}
					
					try{															
						model.setRowCount(0);                                        // 초기화
						if(!textScan.getText().equals("")){                          // textField에 값이 있으면
						if(gum1 == true && gum2 == true && gum3 == true){            // 콤보박스 3개를 모두 선택했을 경우.
							String str = textScan.getText();                         // textField에 값을 str에 저장.
							String Day = (String) comboBox_3.getSelectedItem()		 // comboBox에서 선택한 숫자들(날짜)를 합하여 000000 형식으로 더함.
									+ (String) comboBox_2.getSelectedItem()
									+ (String) comboBox_1.getSelectedItem();
							for (int i = 0; i < pList.size(); i++) {				 // 생산에서 넘겨준 ArrayList를 가지고있는 pList의 크기만큼 for문을 돌림.
								ProductData ds = pList.get(i);						 // ArrayList형식의 데이터를 첫번째부터 ds에 저장
								String Day2 = ds.getNal();							 // 첫번째의 날짜값과 이름값을 가지고옴.
								String Irum = ds.getName();
								Day2 = Day2.substring(0, 6);						 // 날짜에서 년 월 일의 6자리만을 비교하기위해 나머지 부분을 잘라냄.
									if(Day.equals(Day2)){							 // 데이터에서 같은 날짜가 있는지 조건문을 검.
										if(str.equals(Irum)){						 // 날짜가 있으면 그중 이름이 같은게 있는지 조건문을 검.
										Vector<String> vec = new Vector<String>();   // 벡터 생성
										vec.add(ds.getName());						 // 벡터에 ArrayList i번째 데이터를 벡터에 저장.
										vec.add(Integer.toString(ds.getVolume()));
										vec.add(ds.getNal());
										vec.add(ds.getCode());
										vec.add(Integer.toString(ds.getPrice()));
										model.addRow(vec);							 // 테이블에 출력.
										}								
									}							
								}
							for (int J = 0; J < sList.size(); J++) {                 // 판매에서 넘겨준 ArrayList를 가지고있는 sList의 크기만큼 for문을 돌림.
								SaleData sd = (SaleData) sList.get(J);				 // ArrayList형식의 데이터를 첫번째부터 sd에 저장
								String Day2 = sd.getSaleDate();						 // 날짜값과 이름값을 가지고 옴.
								String name = sd.getProName();
								Day2 = Day2.substring(0, 6);						 // 날짜에서 년 월 일의 6자리만을 비교하기위해 나머지 부분을 잘라냄. 
									if(Day.equals(Day2)){						     // 데이터에서 같은 날짜가 있는지 조건문을 검.
										if(str.equals(name)){                        // 날짜가 있으면 그중 이름이 같은게 있는지 조건문을 검.
										Vector<String> vec = new Vector<String>();	 // 벡터 생성
										vec.add(sd.getProName());					 // 벡터에 ArrayList i번째 데이터를 벡터에 저장.
										vec.add(Integer.toString(-sd.getSaleEa()));
										vec.add(sd.getSaleDate());
										vec.add(sd.getProCode());
										vec.add(Integer.toString(sd.getProPrice()));
										model.addRow(vec);							 // 테이블에 출력.
										}
									}
								}
						}else if(gum1 == false && gum2 == false && gum3 == false){				
							String str = textScan.getText();
							for (int i = 0; i < pList.size(); i++) {					
							ProductData ds = pList.get(i);
							String Irum = ds.getName();	
								if(str.equals(Irum)){
									Vector<String> vec = new Vector<String>();
									vec.add(ds.getName());
									vec.add(Integer.toString(ds.getVolume()));
									vec.add(ds.getNal());
									vec.add(ds.getCode());
									vec.add(Integer.toString(ds.getPrice()));
									model.addRow(vec);
								}
														
							}
						for (int J = 0; J < sList.size(); J++) {
							SaleData sd = (SaleData) sList.get(J);
							String name = sd.getProName();	
								if(str.equals(name)){
									Vector<String> vec = new Vector<String>();
									vec.add(sd.getProName());
									vec.add(Integer.toString(-sd.getSaleEa()));
									vec.add(sd.getSaleDate());
									vec.add(sd.getProCode());
									vec.add(Integer.toString(sd.getProPrice()));
									model.addRow(vec);
								}
								
							}
						}else if(gum1 == true && gum2 == false && gum3 == false){				
							String str = textScan.getText();
							String Day = (String) comboBox_3.getSelectedItem();
							for (int i = 0; i < pList.size(); i++) {
							ProductData ds = pList.get(i);
							String Day2 = ds.getNal();	
							String Irum = ds.getName();
							Day2 = Day2.substring(0, 2);
								if(Day.equals(Day2)){
									if(str.equals(Irum)){
									Vector<String> vec = new Vector<String>();
									vec.add(ds.getName());
									vec.add(Integer.toString(ds.getVolume()));
									vec.add(ds.getNal());
									vec.add(ds.getCode());
									vec.add(Integer.toString(ds.getPrice()));
									model.addRow(vec);
									}
								}					
							}
						for (int J = 0; J < sList.size(); J++) {
							SaleData sd = (SaleData) sList.get(J);
							String name = sd.getProName();	
							String Day2 = sd.getSaleDate();
							Day2 = Day2.substring(0, 2);
								if(str.equals(name)){
									if(Day.equals(Day2)){
									Vector<String> vec = new Vector<String>();
									vec.add(sd.getProName());
									vec.add(Integer.toString(-sd.getSaleEa()));
									vec.add(sd.getSaleDate());
									vec.add(sd.getProCode());
									vec.add(Integer.toString(sd.getProPrice()));
									model.addRow(vec);
									
									}
								}
							}
						}else if(gum1 == true && gum2 == true && gum3 == false){				
							String str = textScan.getText();
							String Day = (String) comboBox_3.getSelectedItem()
									+ (String) comboBox_2.getSelectedItem();
							for (int i = 0; i < pList.size(); i++) {
									ProductData ds = pList.get(i);
									String Day2 = ds.getNal();	
									String Irum = ds.getName();
									Day2 = Day2.substring(0, 4);
										if(Day.equals(Day2)){
											if(str.equals(Irum)){
											Vector<String> vec = new Vector<String>();
											vec.add(ds.getName());
											vec.add(Integer.toString(ds.getVolume()));
											vec.add(ds.getNal());
											vec.add(ds.getCode());
											vec.add(Integer.toString(ds.getPrice()));
											model.addRow(vec);
											}
										
								}							
							}
						for (int J = 0; J < sList.size(); J++) {
							SaleData sd = (SaleData) sList.get(J);
							String name = sd.getProName();	
							String Day2 = sd.getSaleDate();
							Day2 = Day2.substring(0, 4);
								if(str.equals(name)){
									if(Day.equals(Day2)){
									Vector<String> vec = new Vector<String>();
									vec.add(sd.getProName());
									vec.add(Integer.toString(-sd.getSaleEa()));
									vec.add(sd.getSaleDate());
									vec.add(sd.getProCode());
									vec.add(Integer.toString(sd.getProPrice()));
									model.addRow(vec);
									}
								}
							}
						}
						}
						//
						//
						//
					//
						if(textScan.getText().equals("")){
							
						if(gum1 == true && gum2 == false && gum3 == false){
							String Day = (String) comboBox_3.getSelectedItem();
							for (int i = 0; i < pList.size(); i++) {
								ProductData ds = pList.get(i);
								String Day2 = ds.getNal();	
								Day2 = Day2.substring(0, 2);
									if(Day.equals(Day2)){
										Vector<String> vec = new Vector<String>();
										vec.add(ds.getName());
										vec.add(Integer.toString(ds.getVolume()));
										vec.add(ds.getNal());
										vec.add(ds.getCode());
										vec.add(Integer.toString(ds.getPrice()));
										model.addRow(vec);
									}						
								}
							for (int J = 0; J < sList.size(); J++) {
								SaleData sd = (SaleData) sList.get(J);
								String Day2 = sd.getSaleDate();	
								Day2 = Day2.substring(0, 2);
									if(Day.equals(Day2)){
										Vector<String> vec = new Vector<String>();
										vec.add(sd.getProName());
										vec.add(Integer.toString(-sd.getSaleEa()));
										vec.add(sd.getSaleDate());
										vec.add(sd.getProCode());
										vec.add(Integer.toString(sd.getProPrice()));
										model.addRow(vec);
										}								
									}					
							}else if(gum1 == true && gum2 == true && gum3 == false){
								String Day = (String) comboBox_3.getSelectedItem()
												+ (String) comboBox_2.getSelectedItem();
								for (int i = 0; i < pList.size(); i++) {
									ProductData ds = pList.get(i);
									String Day2 = ds.getNal();	
									Day2 = Day2.substring(0, 4);
										if(Day.equals(Day2)){
											Vector<String> vec = new Vector<String>();
											vec.add(ds.getName());
											vec.add(Integer.toString(ds.getVolume()));
											vec.add(ds.getNal());
											vec.add(ds.getCode());
											vec.add(Integer.toString(ds.getPrice()));
											model.addRow(vec);	
										}						
									}
								for (int J = 0; J < sList.size(); J++) {
									SaleData sd = (SaleData) sList.get(J);
									String Day2 = sd.getSaleDate();	
									Day2 = Day2.substring(0, 4);
										if(Day.equals(Day2)){
											Vector<String> vec = new Vector<String>();
											vec.add(sd.getProName());
											vec.add(Integer.toString(-sd.getSaleEa()));
											vec.add(sd.getSaleDate());
											vec.add(sd.getProCode());
											vec.add(Integer.toString(sd.getProPrice()));
											model.addRow(vec);
											}
								}
							}else if(gum1 == true && gum2 == true && gum3 == true){
								String Day = (String) comboBox_3.getSelectedItem()
												+ (String) comboBox_2.getSelectedItem()
													+ (String) comboBox_1.getSelectedItem();
								for (int i = 0; i < pList.size(); i++) {
									ProductData ds = pList.get(i);
									String Day2 = ds.getNal();	
									Day2 = Day2.substring(0, 6);
										if(Day.equals(Day2)){
											Vector<String> vec = new Vector<String>();
											vec.add(ds.getName());
											vec.add(Integer.toString(ds.getVolume()));
											vec.add(ds.getNal());
											vec.add(ds.getCode());
											vec.add(Integer.toString(ds.getPrice()));
											model.addRow(vec);									
										}						
									}
								for (int J = 0; J < sList.size(); J++) {
									SaleData sd = (SaleData) sList.get(J);
									String Day2 = sd.getSaleDate();	
									Day2 = Day2.substring(0, 6);
										if(Day.equals(Day2)){
											Vector<String> vec = new Vector<String>();
											vec.add(sd.getProName());
											vec.add(Integer.toString(-sd.getSaleEa()));
											vec.add(sd.getSaleDate());
											vec.add(sd.getProCode());
											vec.add(Integer.toString(sd.getProPrice()));
											model.addRow(vec);
											}
									}
								}
							}
						}catch(Exception ex){
							JOptionPane.showMessageDialog(null, "검색내용을 입력하세요. 제발~ ");
						}			
				}
			});
		}
		return btnScan;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}
	private JTable getTable() {
		if (table == null) {
			model = new DefaultTableModel() { // 여기 넣으니까 작동
							public boolean isCellEditable(int r, int c){ // 테이블 편집불가능하게 한다. 
								  return false ;
							 }
						};

						model.addColumn("제품명");
						model.addColumn("수량");
						model.addColumn("날짜"); // if 생산즉시 입력된다면, 날짜를 하나만 넣어도 됨
						model.addColumn("제품코드");
						model.addColumn("가격");
										
				table = new JTable(model);
				
				table.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						columnX = table.getSelectedColumn();
						rowY = table.getSelectedRow();
						if (table.getColumnName(columnX).equals("수량") || table.getColumnName(columnX).equals("가격")) {
//							circleOpen();
						}
						else {
						findText = (String) table.getValueAt(rowY, columnX);
						scan();
						}
					}
				});
				table.setAutoCreateRowSorter(true);
				TableRowSorter tableSorter = new TableRowSorter(table.getModel());
				table.setRowSorter(tableSorter);
//				table.getRowSorter().toggleSortOrder(4);

		}
		return table;
	}
	
	void circleOpen() {
		if (test==null) {
//		int jeago = Integer.parseInt((String) table.getValueAt(rowY, columnX));
		test = new GraphicsObjectEx(circleJeago, circlePro); // 일단 임의로 1000 넣고 // 1000넣어도 소용없음
		test.setLocation(test.getX()+50, test.getY()+test.getHeight()+100);
		test.setVisible(true);
		}
		else {
			test.dispose();
			test=null;
			circleOpen();
		}
	}
	
	void scan() {
			
		if (tb==null) { // 창이 없으면
		tb = new Stock2(findText, join); // 그냥 Re의 생성자에 검색 메소드를 때려박자
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //프레임의 크기 구함
		tb.setLocation(table.getWidth(), tb.getHeight());
		tb.setVisible(true);
		}
		else {
			tb.dispose();
			tb=null;
			scan();
		}
	}
	private JMenuBar getMenuBar_1() {
		if (menuBar == null) {
			menuBar = new JMenuBar();
			menuBar.add(getBtnNewButton());
			menuBar.add(getBtnNewButton_2());
			menuBar.add(getPanel_1());
			menuBar.add(getButton());
			menuBar.add(getBtnNewButton_1());
		}
		return menuBar;
	}
	
	void load() {
		try {
					model.setNumRows(0);
			
					File f = new File("ProductList.dat");
					
//					File f = new File("c:\\ProductList.dat");
					
					if(f.exists()) lblNewLabel.setVisible(true);
					else JOptionPane.showMessageDialog(null, "c:ProductList.dat 파일이 없습니다");
					
					fis = new FileInputStream(f);
					ois = new ObjectInputStream(fis);;
					
					pList = (ArrayList) ois.readObject();
					
					v = new Vector();
					v.addAll(pList);			
					for (ProductData s : v) { 
						String[] temp = {s.getName(), ""+s.getVolume(), s.getNal(), s.getCode(), ""+s.getPrice()}; //코드, 이름, 수량, 가격, 날짜
						model.addRow(temp);
					}
					
//					File f2 = new File("SaleList.dat");
/*					File f2 = new File("c:\\SaleList.dat");
					
					if(f2.exists()) lblNewLabel_1.setVisible(true);
					else JOptionPane.showMessageDialog(null, "SaleList.dat 파일이 없습니다");
					
					fis = new FileInputStream(f2);
					ois = new ObjectInputStream(fis);;

					sList = (ArrayList) ois.readObject();
						
					v2 = new Vector();
					v2.addAll(sList);
					for (SaleData s : v2) { 
						String[] temp = {s.getProName(), "-"+s.getSaleEa(), s.getSaleDate(), s.getProCode(), ""+s.getProPrice()}; 
						model.addRow(temp);
					}*/
					
				join = new HashMap();
				
				for (int i = 0; i < table.getRowCount(); i++) {
					ProductData stock = new ProductData((String)table.getValueAt(i, 0), // 처음 로딩할 때 딱 한번만 에러 뜸
							Integer.parseInt((String)table.getValueAt(i, 1)), (String)table.getValueAt(i, 2), 
							(String)table.getValueAt(i, 3), Integer.parseInt((String)table.getValueAt(i, 4)));
						
						if (join.get(stock.getCode())==null) join.put((String) table.getValueAt(i, 3), stock); //기존에 입력되어 있지 않다면
						else { // 기존에 입력되어 있다면 키에서 숫자를 불러내서 더한다
							ProductData calcStock = join.get(stock.getCode());
							int stockNow = calcStock.getVolume() + stock.getVolume();
							stock = new ProductData(table.getValueAt(i, 0)+"", stockNow, table.getValueAt(i, 2)+"", table.getValueAt(i, 3)+"", Integer.parseInt((String)table.getValueAt(i, 4))); 
							join.put(stock.getCode(), stock);
						}
				}
				
				setTitle("전체 내역");
				
				findText = "LOAD";
				Stock2 tb = new Stock2(findText, join); // 그냥 Re의 생성자에 검색 메소드를 때려박자
				tb.setLocation(20+table.getWidth(), tb.getY());
				tb.setVisible(true);
				
				circlePro=0;
				Set<String> s = join.keySet();
				Iterator i = s.iterator();
				while (i.hasNext()) {
					String key = (String) i.next();
					ProductData jValue = (ProductData) join.get(key);
					circlePro += jValue.getVolume();
				}
				System.out.println(circlePro + "총 재고");
				
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			try{
				ois.close();
				fis.close();
			}catch(Exception ex2){}
		}
	}
	
	void load2() {
		try {
			File f2 = new File("SaleList.dat");
//			File f2 = new File("c:\\SaleList.dat");
			
			if(f2.exists()) lblNewLabel_1.setVisible(true);
			else JOptionPane.showMessageDialog(null, "SaleList.dat 파일이 없습니다");
			
			fis = new FileInputStream(f2);
			ois = new ObjectInputStream(fis);;

			sList = (ArrayList) ois.readObject();
				
			v2 = new Vector();
			v2.addAll(sList);
			for (SaleData s : v2) { 
				String[] temp = {s.getProName(), "-"+s.getSaleEa(), s.getSaleDate(), s.getProCode(), ""+s.getProPrice()}; 
				model.addRow(temp);
			}
			
			join = new HashMap();
			
			for (int i = 0; i < table.getRowCount(); i++) {
				ProductData stock = new ProductData((String)table.getValueAt(i, 0), // 처음 로딩할 때 딱 한번만 에러 뜸
						Integer.parseInt((String)table.getValueAt(i, 1)), (String)table.getValueAt(i, 2), 
						(String)table.getValueAt(i, 3), Integer.parseInt((String)table.getValueAt(i, 4)));
					
					if (join.get(stock.getCode())==null) join.put((String) table.getValueAt(i, 3), stock); //기존에 입력되어 있지 않다면
					else { // 기존에 입력되어 있다면 키에서 숫자를 불러내서 더한다
						ProductData calcStock = join.get(stock.getCode());
						int stockNow = calcStock.getVolume() + stock.getVolume();
						stock = new ProductData(table.getValueAt(i, 0)+"", stockNow, table.getValueAt(i, 2)+"", table.getValueAt(i, 3)+"", Integer.parseInt((String)table.getValueAt(i, 4))); 
						join.put(stock.getCode(), stock);
					}
			}
			
			setTitle("전체 내역");
			
			findText = "LOAD";
			Stock2 tb = new Stock2(findText, join); // 그냥 Re의 생성자에 검색 메소드를 때려박자
			tb.setLocation(20+table.getWidth(), tb.getY());
			tb.setVisible(true);
			
			circleJeago=0;
			Set<String> s = join.keySet();
			Iterator i = s.iterator();
			while (i.hasNext()) {
				String key = (String) i.next();
				ProductData sValue = (ProductData) join.get(key);
				circleJeago += sValue.getVolume();
			}
			circleJeago = circlePro - circleJeago;
			System.out.println(circleJeago + "총 판매");
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setBackground(new Color(152, 251, 152));
			panel_1.add(getLblNewLabel());
			panel_1.add(getLblNewLabel_1());
			panel_1.add(getLblNewLabel_3());
		}
		return panel_1;
	}
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("Production");
			lblNewLabel.setVisible(false);
			lblNewLabel.setFont(new Font("굴림", Font.BOLD, 14));
		}
		return lblNewLabel;
	}
	private JLabel getLblNewLabel_1() {
		if (lblNewLabel_1 == null) {
			lblNewLabel_1 = new JLabel(" Sale");
			lblNewLabel_1.setVisible(false);
			lblNewLabel_1.setFont(new Font("굴림", Font.BOLD, 14));
		}
		return lblNewLabel_1;
	}
	private JLabel getLblNewLabel_3() {
		if (lblNewLabel_3 == null) {
			lblNewLabel_3 = new JLabel(" TotalSale");
			lblNewLabel_3.setVisible(false);
			lblNewLabel_3.setFont(new Font("굴림", Font.BOLD, 14));
		}
		return lblNewLabel_3;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("생산");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					load();
				}
			});
		}
		return btnNewButton;
	}
	private JButton getButton() {
		if (button == null) {
			button = new JButton("결산");
			button.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					
					Exception dunjer = new Exception();
					
					if (v2==null) {
						JOptionPane.showMessageDialog(null, "판매 내역을 입력해주세요");
						try {
							throw dunjer;
						} catch (Exception e) {

							e.printStackTrace();
						}
					}
					
					try {
						File f3 = new File("SaleTotal.dat");
//						File f3 = new File("c:\\SaleTotal.dat");
						
						if(f3.exists()) lblNewLabel_3.setVisible(true);
						else {
							JOptionPane.showMessageDialog(null, "SaleTotal.dat 파일이 없습니다");
							throw dunjer;
						}
						
						fis = new FileInputStream(f3);
						ois = new ObjectInputStream(fis);;
						
						sTotal = (HashMap) ois.readObject();
						
						Set s = sTotal.keySet();
						Iterator<String> it = s.iterator();
						
						Date t = new Date();
						SimpleDateFormat sd = new SimpleDateFormat("yyMMdd");

						model.setNumRows(0);
						
//						circleSale=0; // 원형 그래프의 판매량을 0으로 초기화
						
						while(it.hasNext()) {
							String d =it.next();
							SaleTotal whatever = (SaleTotal) sTotal.get(d);
							String[] temp = {whatever.getProName(), "-"+whatever.getSaleEa(), sd.format(t), whatever.getProCode(), ""+whatever.getProPrice()};
							
//							circleSale += whatever.getSaleEa();	 // 원형 그래프의 판매량을 더함
							
							model.addRow(temp);
						}	

						setTitle("판매측 판매 집계");
						
						String compareTime = sd.format(t);
						Stock2 tb = new Stock2(v2, sTotal, compareTime);
						tb.setLocation(tb.getX()+tb.getWidth()*2, tb.getY());
						tb.setVisible(true);

//						System.out.println(circleSale + "총 판매");
						
						circleOpen();
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
		return button;
	}
	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.add(getBtnSaveExcel());
			panel_2.add(getComboBox_3());
			panel_2.add(getLabel());
			panel_2.add(getComboBox_2());
			panel_2.add(getLblNewLabel_2());
			panel_2.add(getComboBox_1());
			panel_2.add(getLabel_1());
			panel_2.add(getTextScan());
		}
		return panel_2;
	}
	private JComboBox getComboBox_1() {
		if (comboBox_1 == null) {
			comboBox_1 = new JComboBox();
			comboBox_1.setEnabled(false);
			comboBox_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					gum3 = true;
				}
			});
			comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"", "01", "02", "03", "04", "05", "06",
					             "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
					                "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
		}
		return comboBox_1;
	}
	private JComboBox getComboBox_2() {
		if (comboBox_2 == null) {
			comboBox_2 = new JComboBox();
			comboBox_2.setEnabled(false);
			comboBox_2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					gum2 = true;
					comboBox_1.setEnabled(true);	
				}
			});
			comboBox_2.setModel(new DefaultComboBoxModel(new String[] {"", "01", "02", "03", "04", "05", "06", "07",
					                                                                 "08", "09", "10", "11", "12"}));
		}
		return comboBox_2;
	}
	private JComboBox getComboBox_3() {
		if (comboBox_3 == null) {
			comboBox_3 = new JComboBox();
			comboBox_3.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					gum1 = true;
					comboBox_2.setEnabled(true);
				}
			});
			comboBox_3.setModel(new DefaultComboBoxModel(new String[] {"", "11", "12", "13", "14", "15", "16", "17"}));
		}
		return comboBox_3;
	}
	private JTextField getTextScan() {
		if (textScan == null) {
			textScan = new JTextField();
			textScan.setColumns(10);
		}
		return textScan;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("년");
		}
		return label;
	}
	private JLabel getLblNewLabel_2() {
		if (lblNewLabel_2 == null) {
			lblNewLabel_2 = new JLabel("월");
		}
		return lblNewLabel_2;
	}
	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("일");
		}
		return label_1;
	}
	private JButton getBtnSaveExcel() {
		if (btnSaveExcel == null) {
			btnSaveExcel = new JButton("엑셀로 저장");
			btnSaveExcel.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					saveExcel();					
					
					JOptionPane.showMessageDialog(null, FilePath + " 에 파일이 저장되었습니다.");
				}
			});
		}
		return btnSaveExcel;
	}
	
	
	public void saveExcel(){
		String[] getColumn = new String[table.getColumnCount()];
		for(int i=0; i<table.getColumnCount(); i++){ //컬럼명 받기
			getColumn[i] = table.getColumnName(i);
		}
		
		String[][] getData = new String[table.getRowCount()][table.getColumnCount()]; //데이터받기
		for(int i=0; i<table.getRowCount(); i++){
			for(int j=0; j<table.getColumnCount(); j++){
				getData[i][j] = (String)table.getValueAt(i,j);
			}
		}
		
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(new File(FilePath)); //파일경로설정
			WritableSheet sheet = workbook.createSheet(SheetName, 0); // 시트이름과 시트번호
			
			jxl.write.WritableCellFormat columnFormat = new WritableCellFormat(); //컬럼포맷 스트링.
			jxl.write.WritableCellFormat dataFormat  = new WritableCellFormat(); //데이터포맷 스트링.
			 
			columnFormat.setBackground(jxl.format.Colour.ORANGE); //컬럼포맷 백그라운드 색상설정.
			
			for(int i=0; i<getColumn.length; i++){ //컬럼명 넣어주기.
				jxl.write.Label label = new jxl.write.Label(i, 0, getColumn[i], columnFormat); //(열,행,컬럼명,스트링포맷)
				 sheet.addCell(label);
			}
			
			for(int i=0; i<getData.length; i++){
				for(int j=0; j<getData[i].length; j++){
					jxl.write.Label lbl = new jxl.write.Label(j, i+1, getData[i][j], dataFormat); //(열,행,데이터,스트링포맷)
					sheet.addCell(lbl);
				}
			}
			
			workbook.write();
			workbook.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	private JButton getBtnNewButton_1() {
		if (btnNewButton_1 == null) {
			btnNewButton_1 = new JButton("차트");
			btnNewButton_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					LineBarChart graph = new LineBarChart();
					JFreeChart chart = graph.getChart();
					ChartFrame frame1 = new ChartFrame("재고 그래프", chart);
					frame1.setSize(900, 500);
					frame1.getChartPanel().setLayout(null);
					frame1.getContentPane().setLayout(null);
					frame1.setVisible(true);
				}
			});
		}
		return btnNewButton_1;
	}
	private JButton getBtnNewButton_2() {
		if (btnNewButton_2 == null) {
			btnNewButton_2 = new JButton("판매");
			btnNewButton_2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					load2();
				}
			});
		}
		return btnNewButton_2;
	}
}